package com.bdqn.BookManage.servlet;


import com.bdqn.BookManage.biz.BookInfoBiz;
import com.bdqn.BookManage.biz.BookTypeBiz;
import com.bdqn.BookManage.biz.impl.BookInfoBizImpl;
import com.bdqn.BookManage.biz.impl.BookTypeBizImpl;
import com.bdqn.BookManage.po.BookInfo;
import com.bdqn.BookManage.po.BookType;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author : CP
 * @version: 1.0
 * @program : BookManage
 * @description : 图书信息查询处理器
 * @date : 2020-07-20 16:06
 **/
@WebServlet("/queryBook")
public class QueryBookInfoAllServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    /**
     * 查询所有图书信息
     * @param req 请求
     * @param resp 响应
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 设置编码集 */
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();

        /* 页码 */
        int number = 0;
        /* 总页码 */
        int pageNumber = 0;


        BookInfoBiz bookInfoBiz = new BookInfoBizImpl();
        BookTypeBiz bookTypeBiz = new BookTypeBizImpl();


        /* 判断是否根据书名查询 */
        String name = req.getParameter("name");
        if(name!=null){
            session.setAttribute ("bookName", name);
        }

        String bookName = (String) session.getAttribute("bookName");


        /* 获取总页码数 */
        pageNumber = bookInfoBiz.queryCount(bookName==null?"":bookName);
        /* 总页码=(总记录数+显示记录数-1)/显示记录数 */
        pageNumber = (pageNumber+2-1)/2;

        /* 获取当前页码 */
        String numberStr = req.getParameter("number");
        number = numberStr == null ? 1 : Integer.valueOf(numberStr);

        /* 查询结果 */
        List<BookType> typeList = bookTypeBiz.queryAll();
        List<BookInfo> list = bookInfoBiz.fuzzyQueryByBookName(bookName==null?"":bookName,number);


        /* 判断是否有查询到数据 */
        if(list.size() == 0){ number=0; }

        /* 保存当前页码 */
        req.setAttribute("number",number);
        /* 保存总页数 */
        req.setAttribute("pageNumber",pageNumber);
        /* 保存集合 */
        req.setAttribute("list",list);
        session.setAttribute("typeList",typeList);

        /* 页面跳转 */
        req.getRequestDispatcher("BookList.jsp").forward(req,resp);

    }
}
